package com.swift.maintenance.utils;

import android.util.Log;
import android.widget.TextView;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Consumer;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;

/**
 * Created by Administrator on 2018/3/16.
 */

public class FlowWordUtil {

    private static final String TAG = FlowWordUtil.class.getName();

    public static void showWord(String word, int time, TimeUnit timeUnit, final TextView tvWord) {
        int count = word.length();
        final List<String> chatList = new ArrayList<>();
        for (int i = 0; i < count; i++) {
            char c = word.charAt(i);
            chatList.add(c + "");
        }

        Log.e(TAG, chatList.toString());

        Observable.interval(time, timeUnit)
                .map(new Function<Long, String>() {
                    @Override
                    public String apply(Long aLong) throws Exception {
                        int index = aLong.intValue();
                        Log.e(TAG, "apply    " + index + "");
                        return chatList.get(index);
                    }
                })
                .take(count)
                .subscribeOn(Schedulers.newThread())
                .unsubscribeOn(Schedulers.newThread())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<String>() {
                    @Override
                    public void accept(String result) throws Exception {
                        Log.e(TAG, "accept    " + result);
                        String currentWord = tvWord.getText().toString();
                        tvWord.setText(currentWord + result);
                        int offset = tvWord.getLineCount() * tvWord.getLineHeight() + tvWord.getPaddingBottom() * 2;
                        if (offset > tvWord.getHeight()) {
                            tvWord.scrollTo(0, offset - tvWord.getHeight());
                        }
                    }
                });
    }
}
